<template>
  <div class="page">
    <div class="page-container">
      <van-nav-bar 
      :title="group.name"
      left-arrow
      @click-left="onClickLeft"
      >
        <template #right>
          <van-icon name="plus" size="18" @click="toAddOrder"/>
        </template>
      </van-nav-bar>
      <van-row v-show="ordersLoading" style="margin-top: 20px;">
        <van-col span="24" align="center">
          <van-loading size="24px">加载中...</van-loading>
          </van-col>
      </van-row>
      <van-swipe-cell v-for="order in orders" :key="order.id" :before-close="beforeClose" >
        <van-cell icon="play-circle-o" @click="orderClick(order)">
            <template #title>
                <span class="custom-title">{{ order.name }}</span>
                <van-tag v-if="!order.code" mark type="danger">未学习</van-tag>
            </template>
        </van-cell>
        <template #right>
          <van-button square type="primary" text="学习" @click="toLearnOrder(order.id)"/>
          <van-button square type="info" text="编辑" @click="toAddOrder(order)"/>
          <van-button square type="danger" text="删除" @click="toDelOrder(order)"/>
        </template>
      </van-swipe-cell>
    </div>
    <van-popup v-model="addOrderShow" round position="bottom">
      <van-form @submit="saveOrder" style="margin: 10px">
        <van-field
          v-model="orderForm.name"
          name="指令名"
          label="指令名"
          placeholder="请填写指令名"
          :rules="[{ required: true, message: '请填写指令名' }]"
          clearable
        />
        <div style="margin: 16px;">
          <van-button :loading="orderSaving" round block type="info" native-type="submit" loading-type="spinner">提交</van-button>
        </div>
      </van-form>
    </van-popup>
    <van-popup v-model="orderTypePicker" position="bottom">
        <van-picker
            show-toolbar
            :columns="orderTypeOptions"
            :default-index="1"
            @confirm="learnOrder"
            @cancel="orderTypePicker = false"
        />
    </van-popup>
    <tab-bar :active-index="0"/>
    <van-overlay :show="loadingLayer">
        <div class="loading-wrapper" @click.stop>
            <van-loading size="24px" color="#0094ff" vertical >{{ loadingLayerText }}</van-loading>
        </div>
    </van-overlay>
  </div>
</template>

<script>
import { Dialog } from 'vant';
import { Notify } from 'vant';
export default {
  data: function () {
    return {
      // enter some data
      group:{name:'-'},
      orders: [], ordersLoading: false,
      addOrderShow: false, orderForm: {}, orderSaving: false,
      loadingLayer: false, loadingLayerText: '...',
      learnForm: {},orderTypePicker: false, orderTypeOptions: ['长红外(空调等)', '短红外(电视，机顶盒，空调扇等)'],
    }
  },
  mounted() {

    this.group.id = this.$route.query.id
    this.group.name = this.$route.query.name
    this.group.deviceId = this.$route.query.deviceId
    if (this.group.id) {
        this.loadOrders()
    }
  },
  methods: {
    // put some function here
    onClickLeft() {
      this.$router.go(-1)
    },
    loadOrders() {
      this.orders = []
      this.ordersLoading = true
      this.$api.request("/order/list",{
        params: {
          groupId: this.group.id
        }
      }).then(response=>{
        if (response.code === 1) {
          this.orders = response.data
        } else {
          Notify({ type: 'warning', message: `查询失败：${response.message}` });
        }
      }).catch(e=>{
          Notify({ type: 'danger', message: '网络请求失败' });
      }).then(()=>{
          this.ordersLoading = false
      })
    },
    // position 为关闭时点击的位置
    // instance 为对应的 SwipeCell 实例
    beforeClose({ position, instance }) {
    //   console.log(position);
      switch (position) {
        case 'left':
        case 'cell':
        case 'outside':
          instance.close();
          break;
        case 'right':
          instance.close();
          break;
      }
    },
    toAddOrder(order) {
      if (order && order.id) {
        this.orderForm = {
            ...order
        }
      } else {
        this.orderForm = {
            groupId: this.group.id,
            deviceId: this.group.deviceId
        }
      }
      this.addOrderShow = true
    },
    saveOrder() {
      this.orderSaving = true
      this.$api.request('/order/save',{
        method: 'POST',
        data: this.orderForm
      }).then(response=>{
        if (response.code === 1) {
            this.addOrderShow = false
            this.orderForm = {}
            this.loadOrders()
            Notify({ type: 'success', message: '保存成功', duration: 1500 });
        } else {
          Notify({ type: 'warning', message: `保存失败：${response.message}` });
        }
      }).catch(e=>{
        Notify({ type: 'warning', message: `网络请求失败：${e.message}` });
      }).then(()=>{
        this.orderSaving = false
      })
    },
    toDelOrder(order) {
      Dialog.confirm({
        // title: '标题',
        message: '确认删除该指令吗?',
      })
        .then(() => {
          // on confirm
          this.loadingLayer = true
          this.loadingLayerText = '删除中...'
          this.$api.request("/order/delete/" + order.id,{
          }).then(response=>{
            if (response.code === 1) {
              Notify({ type: 'success', message: '已删除', duration: 1500 });
              this.loadOrders()
            } else {
              Notify({ type: 'warning', message: `删除失败：${response.message}` });
            }
          }).catch(e=>{
              Notify({ type: 'danger', message: '网络请求失败' });
          }).then(()=>{
              this.loadingLayer = false
          })
        })
        .catch(() => {
          // on cancel
        });
    },
    toLearnOrder(orderId) {
      this.learnForm.id = orderId
      this.orderTypePicker = true
    },
    learnOrder(value, index) {
      this.orderTypePicker = false
      this.loadingLayer = true
      this.loadingLayerText = '学习中...'
      this.$api.request("/order/learn",{
          method: 'POST',
          data: { id: this.learnForm.id, orderType: index }
        }).then(response=>{
        if (response.code === 1) {
          Notify({ type: 'success', message: '学习成功', duration: 1500 });
          this.loadOrders()
        } else {
            Notify({ type: 'warning', message: `学习失败：${response.message}` });
        }
        }).catch(e=>{
            Notify({ type: 'danger', message: '网络请求失败' });
        }).then(()=>{
            this.loadingLayer = false
        })
    },
    orderClick(order) {
      if (!order.code) {
          Dialog.confirm({
            // title: '标题',
            message: '该指令还未学习',
            confirmButtonText: '学习'
          })
          .then(() => {
            // on confirm
            this.toLearnOrder(order.id)
          })
          .catch(() => {
            // on cancel
          });
      } else {
          this.sendOrder(order.id)
      }
    },
    sendOrder(orderId) {
      this.loadingLayer = true
      this.loadingLayerText = '发送中...'
      this.$api.request("/order/send",{
          params: { id: orderId }
        }).then(response=>{
        if (response.code === 1) {
          Notify({ type: 'success', message: '发送成功', duration: 500 });
        } else {
            Notify({ type: 'warning', message: `发送失败：${response.message}` });
        }
        }).catch(e=>{
            Notify({ type: 'danger', message: '网络请求失败' });
        }).then(()=>{
            this.loadingLayer = false
        })
    },
  }
}
</script>
<style scoped>
.loading-wrapper {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
}
</style>
